<template>
  <div class="todo-app">
    <TodoHeader v-model="newTodo" @add-todo="handleAddTodo" />

    <TodoList
      v-model:todos="todos"
      @toggle-todo="toggleTodo"
      @delete-todo="deleteTodo"
      @edit-todo="editTodo"
    />

    <TodoFooter :todos="todos" @clear-completed="clearCompleted" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import TodoHeader from './components/TodoHeader.vue'
import TodoList from './components/TodoList.vue'
import TodoFooter from './components/TodoFooter.vue'

// 从localStorage加载数据
const loadFromLocalStorage = () => {
  const savedTodos = localStorage.getItem('todos')
  if (!savedTodos) return []

  try {
    const todos = JSON.parse(savedTodos)
    // 验证数据结构
    return todos.filter(
      (todo) =>
        todo &&
        typeof todo.id === 'number' &&
        typeof todo.text === 'string' &&
        typeof todo.completed === 'boolean'
    )
  } catch (error) {
    console.error('Failed to parse todos from localStorage:', error)
    return []
  }
}

// 保存数据到localStorage
const saveToLocalStorage = (todos) => {
  localStorage.setItem('todos', JSON.stringify(todos))
}

const todos = ref(loadFromLocalStorage())
const newTodo = ref('')

// 监听todos变化并保存
watch(
  todos,
  (newTodos) => {
    saveToLocalStorage(newTodos)
  },
  { deep: true }
)

onMounted(() => {
  // 组件挂载时已从localStorage加载数据
})

const handleAddTodo = () => {
  if (newTodo.value.trim()) {
    todos.value.push({
      id: Date.now(),
      text: newTodo.value.trim(),
      completed: false,
    })
    newTodo.value = ''
    // 添加后会自动触发watch保存
  }
}

const toggleTodo = (id) => {
  const todo = todos.value.find((t) => t.id === id)
  if (todo) {
    todo.completed = !todo.completed
    // 修改后会自动触发watch保存
  }
}

const deleteTodo = (id) => {
  todos.value = todos.value.filter((t) => t.id !== id)
  // 修改后会自动触发watch保存
}

const clearCompleted = () => {
  todos.value = todos.value.filter((t) => !t.completed)
  // 修改后会自动触发watch保存
}

const editTodo = ({ id, text }) => {
  const todo = todos.value.find((t) => t.id === id)
  if (todo) {
    todo.text = text
    // 修改后会自动触发watch保存
  }
}
</script>

<style scoped>
.todo-app {
  max-width: 600px;
  margin: 0 auto;
  padding: 2rem;
  font-family: Arial, sans-serif;
}
</style>
